package com.perceptivesoftware.licensing.server.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.perceptivesoftware.licensing.TextEncryptUtil;
import com.perceptivesoftware.licensing.client.common.util.SystemParmType;
import com.perceptivesoftware.licensing.client.dto.SystemParmDTO;
import com.perceptivesoftware.licensing.dao.TwParmvalDaoExt;
import com.perceptivesoftware.licensing.domain.generated.TwParmval;

@Transactional
@Component
public class SystemServiceUtil
{

	@Autowired
	private TwParmvalDaoExt TwParmvalDaoExt;

	/**
	 * Creates a dto to represent the hibernate entity.
	 * 
	 * @param Tw
	 * @return
	 */
	public SystemParmDTO getSystemParmDTO(TwParmval Tw)
	{
		final SystemParmDTO dto = new SystemParmDTO();

		dto.setId(SystemParmType.getEnumForType(Tw.getParmvalParmCode()));
		dto.setParmVal(TextEncryptUtil.decode(Tw.getParmvalValue()));

		return dto;
	}

	/**
	 * Creates a dto to represent the hibernate entity.
	 * 
	 * @param type
	 * @return
	 */
	public SystemParmDTO getSystemParmById(SystemParmType type)
	{
		final TwParmval TwParmval = TwParmvalDaoExt.findById(type.getVal());

		if (TwParmval != null)
		{
			return getSystemParmDTO(TwParmval);
		}

		return null;
	}

	/**
	 * Saves the incoming DTO to the database. If a record already exists with the corresponding ID it will update the existing record, otherwise it generate a
	 * new SystemParmDTO record.
	 * 
	 * @param dto
	 * @return
	 */
	public SystemParmDTO saveSystemParm(SystemParmDTO dto)
	{
		TwParmval TwParmval;
		boolean newParm = false;

		TwParmval = TwParmvalDaoExt.findById(dto.getId().getVal());

		if (TwParmval == null)
		{
			newParm = true;
			TwParmval = new TwParmval();
			TwParmval.setParmvalParmCode(dto.getId().getVal());
		}

		TwParmval.setParmvalValue(TextEncryptUtil.encode(dto.getParmVal()));

		if (newParm)
		{
			TwParmvalDaoExt.save(TwParmval);
		}
		else
		{
			TwParmvalDaoExt.update(TwParmval);
		}

		return getSystemParmDTO(TwParmval);
	}

	/**
	 * Attempts to delete the database record corresponding to the given SystemParmDTO
	 * 
	 * @param dto
	 * @return
	 */
	public Boolean deleteSystemParm(SystemParmDTO dto)
	{
		final TwParmval TwParmval = TwParmvalDaoExt.findById(dto.getId().getVal());

		if (TwParmval == null)
		{
			return false;
		}

		TwParmvalDaoExt.delete(TwParmval);

		return true;
	}
}
